package topology;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.LocalDRPC;
import backtype.storm.StormSubmitter;
import backtype.storm.drpc.LinearDRPCTopologyBuilder;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;

public class AccountTopology {
	public static final String url = "jdbc:postgresql://localhost:5432/XXXXXXXX";
	public static final String user = "XXXXXXXX";
	public static final String pass = "XXXXXXXX";
	public static final String username = "XXXXXXXX";
	public static final String payment = "XXXXXXXX";
	public static final String servicename = "XXXXXXXX";
	
	public static class AccountBolt extends BaseBasicBolt {
		@Override
		public void execute(Tuple tuple, BasicOutputCollector collector) {
			String input = tuple.getString(1);
			try {
				
				JSONParser parser = new JSONParser();
				JSONObject obj = (JSONObject)parser.parse(input);
				
				Connection conn = DriverManager.getConnection(url,user,pass);
				PreparedStatement ps = conn.prepareStatement("insert into account ( username , payment ) values (?,?)");
				ps.setString(1, obj.get(username).toString());
				ps.setInt(2, Integer.valueOf(obj.get(payment).toString()));
				ps.executeUpdate();
				ps.close();
				conn.close();
				
				collector.emit(new Values(tuple.getValue(0), "ok:" + input));
				
			} catch (Exception e) {
				collector.emit(new Values(tuple.getValue(0), "error:" + input + ":" + e.getMessage()));
			}
		}

		@Override
		public void declareOutputFields(OutputFieldsDeclarer declarer) {
			declarer.declare(new Fields("id", "result"));
		}
	}

	public static void main(String[] args) throws Exception {
		LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder(servicename);
		builder.addBolt(new AccountBolt(), 3);

		Config conf = new Config();

		if (args == null || args.length == 0) {
            LocalDRPC drpc = new LocalDRPC();
            LocalCluster cluster = new LocalCluster();
            
            cluster.submitTopology("drpc-demo", conf, builder.createLocalTopology(drpc));
            String result = drpc.execute(servicename, "{\"username\" : \"test\",\"payment\" : 10}");
            
            cluster.shutdown();
            drpc.shutdown();
		} else {
			conf.setNumWorkers(3);
			StormSubmitter.submitTopology(args[0], conf, builder.createRemoteTopology());
		}
	}

}
